#include "stdafx.h"
#include "ModelManager.h"

CModelManager gModelManager;


CModelManager::CModelManager()
{
	TRACE("CModelManager::CModelManager");

	// create URL to the IFC-schema in the programs folder
    int step = 1;
	while (step)
    {
        char* localdir = new char[200 *step];
        int size = GetModuleFileName(NULL, localdir, 200);
        if (size <= ((200 * step) - 30))
        {
			m_SchemaFile = new char[200 * step + 20];
            CString dirstr(localdir, size);
            dirstr.Delete(dirstr.ReverseFind('\\'), size - dirstr.ReverseFind('\\'));
			sprintf(m_SchemaFile, "%s\\IFC2x3_TC1.exp", dirstr.GetBuffer());
			step = 0;
        }
        else
            step++;
        free(localdir);
    }	
}

CModelManager::~CModelManager()
{
	TRACE("CModelManager::~CModelManager");

	std::list<CModel*>::iterator it = m_models.begin();
	for (; it != m_models.end(); ++it)
	{
		(*it)->CloseModel();
		delete (*it);
	}
    delete[] m_SchemaFile;	
}

CModel* CModelManager::FindModel(CString URI)
{
	TRACE("CModelManager::FindModel");

	std::list<CModel*>::iterator it = m_models.begin();
	for (; it != m_models.end(); ++it)
	{
		if (URI == (*it)->m_URI)
			return *it;
	}
	return NULL;
}


CModel* CModelManager::AddModel(CString URI)
{
	TRACE("CModelManager::AddModel");

	CModel *model = FindModel(URI); 
	if (model == NULL)
	{
		if (URI.Right(3) == "ifc" || URI.Right(3) == "IFC" || URI.Right(3) == "Ifc" ||
			URI.Right(6) == "ifcxml" || URI.Right(6) == "ifcXML" || URI.Right(6) == "ifcXml"||
			URI.Right(6) == "IFCxml" || URI.Right(6) == "IFCXML" || URI.Right(6) == "IFCXml"||
			URI.Right(6) == "Ifcxml" || URI.Right(6) == "IfcXML" || URI.Right(6) == "IfcXml")
		{
			model = new CIfcModel;
			((CIfcModel*)model)->m_schemaFile = m_SchemaFile;
		}
		else
			model = new CGmlModel;

		model->m_URI = new char[URI.GetLength() + 1];
		model->m_filePath = new char[URI.ReverseFind('\\') + 2];
		model->m_fileName = new char[URI.GetLength() - URI.ReverseFind('\\') + 2];

		strcpy(model->m_URI, URI.GetBuffer());
		strcpy(model->m_filePath, URI.Mid(0, URI.ReverseFind('\\') + 1).GetBuffer());
		strcpy(model->m_fileName, URI.Mid(URI.ReverseFind('\\') + 1, URI.GetLength()).GetBuffer());

		m_models.push_back(model);
		model->OpenModel();
	}
	return model;
}

bool CModelManager::RemoveModel(CModel *model)
{
	TRACE("CModelManager::RemoveModel");
	/*
	if (model->m_UsedByDocs.size() == 0)
	{
		// To do (delete data)
		if (model->m_URI != NULL)
			delete[] (model->m_URI);
		if (model->m_filePath != NULL)
			delete[] (model->m_filePath);
		if (model->m_fileName != NULL)
			delete[] (model->m_fileName);
		model->CloseModel();

		m_models.remove(model);


		delete model;
		return true;
	}
	*/
	return false;
}


